<template>
  <div>
    <a-tabs v-model:activeKey="activeKey" tab-position="left">
      <a-tab-pane key="baseInfo" tab="基础信息" style="height: 200px">
        <a-form
        ref="formRef"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        :model="proceStore.procInfo"
        @finish="onFinish"
      >
        <a-row :gutter="22" style="margin-left: 0px;margin-right: 0px;">
            <a-col :span="11">
                <a-form-item  label="流程名称" name="name">
                    <a-input v-model:value="proceStore.procInfo.name" @change="updateBaseInfo('name')"></a-input>
                </a-form-item>
            </a-col>
            <a-col :span="11">
                <a-form-item  label="流程Key" name="key	">
                    <a-input v-model:value="proceStore.procInfo.key" readOnly></a-input>
                </a-form-item>
            </a-col>
            <a-col :span="11">
                <a-form-item  label="流程类别" name="sortId">
                    <a-tree-select
                        v-model:value="proceStore.procInfo.sortId"
                        placeholder="请选择"
                        :tree-data="nodeSortOptions"
                        defaultValue=""
                    />
                </a-form-item>
            </a-col>
            <a-col :span="11">
                <a-form-item  label="标题生成规则" name="titleModel	">
                    <a-input v-model:value="proceStore.procInfo.titleModel"></a-input>
                </a-form-item>
            </a-col>
            <a-col :span="11">
                <a-form-item  label="表单类型" name="form_type	">
                  <a-select
                    v-model:value="proceStore.procInfo.form_type"
                  >
                    <a-select-option value="0">内置表单</a-select-option>
                    <a-select-option value="1">外部表单</a-select-option>
                  </a-select>
                </a-form-item>
            </a-col>
            <a-col v-if="proceStore.procInfo.form_type==='0'" :span="11">
                <a-form-item  label="流程表单" name="formId">
                  <a-tree-select
                        v-model:value="proceStore.procInfo.formId"
                        placeholder="请选择"
                        :tree-data="nodeFormOptions"
                        defaultValue=""
                    />
                </a-form-item>
            </a-col>
            <a-col v-if="proceStore.procInfo.form_type==='1'" :span="11">
                <a-form-item  label="表单地址" name="form_url	">
                    <a-input v-model:value="proceStore.procInfo.form_url"></a-input>
                </a-form-item>
            </a-col>
            <a-col :span="11" >
                        <a-form-item  label="流程图标" name="picture">
                        <a-upload
                            v-model:file-list="fileList"
                            name="file"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :action="api.uploadfiles"
                            :before-upload="beforeUpload"
                            @change="handleChange"
                        >
                        <img v-if="proceStore.procInfo.picture" :src="proceStore.procInfo.picture" alt="avatar" />
                         <div v-else>
                            <loading-outlined v-if="loading"></loading-outlined>
                            <plus-outlined v-else></plus-outlined>
                            <div class="ant-upload-text">上传图片</div>
                        </div>
                        </a-upload>
                        </a-form-item>
                    </a-col>
        </a-row>
      </a-form>
      </a-tab-pane>
      <a-tab-pane key="flowpower" tab="发起权限">
        <a-form
        ref="formRef"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        :model="proceStore.procInfo"
        >
        <a-row :gutter="24" style="margin-left: 0px;margin-right: 0px;">
          <a-col :span="12">
            <a-form-item label="权限设置">
              <a-select
              ref="select"
              v-model:value="proceStore.procInfo.startPower"
              >
                <a-select-option value="0">所有人都可发起</a-select-option>
                <a-select-option value="1">设置发起范围</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-left: 0px;margin-right: 0px;" v-if="proceStore.procInfo.startPower==='1'">
          <a-col :span="12">
            <a-form-item label="发起范围">
                <div  style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
                <a-space>
                  <div style="overflow: auto;" class="tagboxs">
                    <a-tag closable @close="handleClose(tag)" v-for="tag in proceStore.procInfo.powerData" :key="tag">
                      {{ tag.NAME }}
                    </a-tag>
                  </div>
                </a-space>
                <a-button style="margin-left: auto;" size="small" secondary type="info" @click="openMenuModal">
                  <template #icon>
                    <a-icon><svg-icon name="touxiang" size="18" /></a-icon>
                  </template>请选择
                </a-button>
              </div>
              </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-left: 0px;margin-right: 0px;">
          <a-col :span="12">
            <a-button style="margin-left: auto;text-align: center;"  secondary type="primary" @click="setFlowPower">保存</a-button>
          </a-col>
        </a-row>
      </a-form>
        
      </a-tab-pane>
      <a-tab-pane key="timedout" tab="超时设置">
        <a-button class="editable-add-btn" type="primary" 
        :icon="h(PlusOutlined)" style="margin-bottom: 8px" 
        @click="openTimeoutModal(null)">新增超时策略</a-button>

        <a-table :columns="columns" :data-source="dataSorce" />
      </a-tab-pane>
      <a-tab-pane key="listener" tab="侦听器"></a-tab-pane>
    </a-tabs>
  </div>
      
  </template>
  <script lang="tsx" setup>
  import { reactive, ref,unref,h } from 'vue';
  import { Button, Space,Modal } from 'ant-design-vue';
  import type { FormInstance } from 'ant-design-vue';
  import { PlusOutlined,DeleteOutlined,EditOutlined } from '@ant-design/icons-vue';
  import editor from '@/store/modules/editor';
  import modeler from '@/store/modules/modeler';
  import {handleTree} from '@/utils/common';
  import { getFlowSortList } from '@/api/flow/sort';
  import {getProcessProperties} from '@/api/deployment/index';
  import {processInfo} from '@/store/modules/processInfo';
  import {getFormTree} from '@/api/form/index';
  import SettingOrg from '@/components/setting/assigneeSetting.vue';
  import TimeoutSetting from '@/components/design/components/Panel/components/SubChild/TimeoutSetting.vue';
  import { useModal } from '@/hooks/useModal/useModal';
  import { setFlowStartPower } from '@/api/flow/index';
  import {TimeoutNode,TimeoutConditions,TimeoutType} from '@/components/design/components/DesignerCommCore/PanelOptions';
  import api from '@/core/permission/modules/form/index';
  import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
  import { message } from 'ant-design-vue';

  const activeKey = ref('baseInfo');
  const expand = ref(false);
  const timeOutRef = ref<any>(null);
  const dataSorce = ref<any>([]);
  const loading=ref<Boolean>(false);
  const proceStore=processInfo();
  const editDrawerBindValue = reactive({
    defaultSelectData: [],
    runType:''
  });
  const [ModalRender, modalRef] = useModal()
  //表单数据
  const nodeFormOptions= ref<[]>();
  const fieldNames={
    children:'children',
    title:'name',
    key:'id'
  };
  //流程图标
  const fileList = ref([]);
  const listenerData = reactive({
        defaultSelectData: {}
      });
  const formRef = ref<FormInstance>();

  const elementObject=modeler();
  //获取流程信息
  const loadProcessInfo= async()=>{
    console.log(proceStore.procInfo,"proceStore.procInfo11111");
    const processInfo=elementObject.elementRegistry?.find((el) => el.type === 'bpmn:Process');
    proceStore.procInfo.sortId=proceStore.procInfo.sortId?proceStore.procInfo.sortId:"";
    proceStore.procInfo.key=processInfo?.id;
    dataSorce.value=proceStore.procInfo.timeoutData?proceStore.procInfo.timeoutData:[];
    // if(proceStore.procInfo.id!==""){
    //   const res=await getProcessProperties({id:proceStore.procInfo.id});
    //   if(res.error=="200"){
    //     proceStore.procInfo.form_type=res.result.form_type;
    //     proceStore.procInfo.form_url=res.result.form_url;
    //     proceStore.procInfo.formId=res.result.formId;
    //     proceStore.procInfo.startPower=res.result.startPower;
    //     proceStore.procInfo.titleModel=res.result.titleModel;
    //     proceStore.procInfo.powerData=JSON.parse(res.result.powerData);
    //   }
    // }
    
  }
  loadProcessInfo();
  const setFormTree = async()=>{
    const res=await getFormTree();
    nodeFormOptions.value=transformTreeData(handleTree(res.result,'id','formSort'));
    console.log(nodeFormOptions.value,"nodeFormOptions.value1111")
  }
  setFormTree();
  //更新流程信息
  const updateBaseInfo=(key)=>{
    const processInfo=elementObject.elementRegistry?.find((el) => el.type === 'bpmn:Process');
    const attrObj=Object.create(null);
    attrObj[key]=flow.name;
    const modeling= modeler().getModeling;
    modeling!.updateProperties(processInfo,attrObj);
  }
  const setFlowPower=async()=>{
    setFlowStartPower({ processInfo:proceStore.procInfo}).then((res) => {
          if (res.error == '200') {
            window.__messageBox.success(res.result);
          } else {
            window.__messageBox.error('设置失败');
          }
        });
  }
  //加载流程类别数据
  const nodeSortOptions= ref<[{}]>();
  const setSelectedTree = async()=>{
    const res=await getFlowSortList();
    nodeSortOptions.value=transSortTreeData(res.result);
  }
  const transSortTreeData = (data: any[]): any[] => {  
    return data.map(node => ({  
        value: node.sortId,  
        label: node.sortName,  
        title: node.sortName, 
        children: node.children ? transSortTreeData(node.children) : undefined,  
    }));  
  };
    const transformTreeData = (data: any[]): any[] => {  
    return data.map(form => ({  
        value: form.id,  
        label: form.name,  
        title: form.name, 
        children: form.children ? transformTreeData(form.children) : undefined,  
    }));  
  };
  const openMenuModal = async()=>{
    editDrawerBindValue.runType="0";
    editDrawerBindValue.defaultSelectData=proceStore.procInfo.powerData;
    ModalRender.show({
      title: '选择处理人',
      width: '70%',
      destroyOnClose: true,
      content: () => {
        return <SettingOrg  ref={modalRef} defaultData={unref(editDrawerBindValue)}></SettingOrg>;
      },
      // 确定方法执行
      onOk: async (values) => {
        const res = await modalRef.value?.handleSubmit();
        console.log(res);
        if (!res) return;
        proceStore.procInfo.powerData=res;
      },
    });
  };
  const openTimeoutModal = async(record)=>{
    ModalRender.show({
      title: '新增超时策略',
      width: '60%',
      destroyOnClose: true,
      content: () => {
        return <TimeoutSetting  ref={timeOutRef} defaultData={listenerData}></TimeoutSetting>;
      },
      // 确定方法执行
      onOk: async (values) => {
        const res = await timeOutRef.value?.handleSubmit();
        if (!res) return;
        let actionName="";
        if(res.executionActions.length>0){
          res.executionActions.map((action) => {
            const labels = TimeoutType
              .filter(item => item.value === action.type)
              .map(item => item.label);

            const actionLabels = labels.length > 0 
            ? labels.join('、') 
            : '未命名';
            
            actionName+=actionLabels+'、';
            console.log(actionName,"executionAction1111111111")
          });
        }
        const timeCond=TimeoutNode.filter((item)=>item.value==res.timeoutNode);
        const timeoutData={
          ...res,
          mypk:uuidv4(),
          timeoutNodeName:timeCond[0].label,
          typeName:actionName.slice(0, -1)
        }
        dataSorce.value.push(timeoutData)
        proceStore.procInfo.timeoutData=dataSorce.value;
        console.log(dataSorce.value,"dataSorce.value22222222222")
      },
    });
  };
  const keyItemColumns = [
    {
      title: '超时名称',
      dataIndex: 'policyName',
      key: 'policyName',
    },
    {
      title: '超时类型',
      dataIndex: 'timeoutNodeName',
      key: 'timeoutNodeName',
      width: '25%',
    },
    {
      title: '执行动作',
      dataIndex: 'typeName',
      key: 'typeName',
      width: '25%',
    }
  ];
  const columns = [
    ...keyItemColumns,
    {
      title: '操作',
      width: 350,
      dataIndex: 'ACTION',
      align: 'center',
      customRender: ({ record }) => {
      return h(Space, [
        h(
          Button,
          {
            onClick: () => openTimeoutModal(record),
            icon: h(EditOutlined),
          },
          '编辑'
        ),
        h(
          Button,
          {
            danger: true,
            onClick: () => removeAction(record),
            icon: h(DeleteOutlined),
          },
          '删除'
        )
      ]);
    },
    },
  ];
  const removeAction = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此策略吗？',
      okText: '确定',
      cancelText: '取消',
      centered: true, 
      onOk() {
        console.log(dataSorce.value,"dataSorce.value3333")
        dataSorce.value=dataSorce.value.filter((item) => item.mypk !==record.mypk)
        proceStore.procInfo.timeoutData=dataSorce.value;
      }
  });
}; 
const handleChange = (info: UploadChangeParam) => {
        console.log(info,"uploadinfo111111111111111")
        if (info.file.status === 'uploading') {
            loading.value = true;
            return;
        }
        if (info.file.status === 'done') {
            if(info.file.response.error=="200"){
              proceStore.procInfo.picture=info.file.response.result.filePath;
            }
            else{
                loading.value = false;
                message.error("上传失败");
            }
            
        }
        if (info.file.status === 'error') {
            loading.value = false;
            message.error("上传失败");
        }
    };
    const beforeUpload = (file: UploadProps['fileList'][number]) => {
        return new Promise<boolean | File>((resolve) => {
            const img = new Image();
            img.src = URL.createObjectURL(file);
            img.onload = () => {
                URL.revokeObjectURL(img.src); 
                if (img.width > 70 || img.height > 70) {
                    message.error("图片尺寸不得大于70x70");
                    resolve(false);
                    return;
                }
                else{
                    resolve(true);
                    return;
                }
            }
        });
        
        
    };
  function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
    /[xy]/g,
    function (c) {
      var r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    }
  );
}

  setSelectedTree();
  setSelectedTree();
  const onSubMit = async () => {
      return flow;
    };

    defineExpose({
      handleSubmit: onSubMit,
    });
  </script>
  